﻿using AutoMapper;
using Domain.Process_Procedures;
using Domain.User;
using Infratructure.Interface;
using MediatR;
using MES.Server.API.Application.Command.Process_Procedures.ProcessFlow;
using ReturnValue;
using System.Transactions;
using Yitter.IdGenerator;

namespace MES.Server.API.Application.Handler.Process_Procedures.ProcessFlow
{
    public class AddProcessFlowHandler : IRequestHandler<AddProcessFlowCommand, ApiResult<int>>
    {
        private readonly IRepository<ProcessFlowModel> _processFlowRepo;
        private readonly IRepository<ProcessManagementModel> _processMqRepo;
        private readonly IRepository<AccountModel> _accRepo;
        private readonly IRepository<DepartmentModel> _deptRepo;
        private readonly IRepository<ProcessFlowDetailModel> processFlowDetailRepo;
        private readonly IMapper _mapper;
        private readonly ILogger<AddProcessFlowHandler> _logger;

        /// <summary>
        /// 注入所需仓储
        /// </summary>
        public AddProcessFlowHandler(
            IRepository<ProcessFlowModel> processFlowRepo,
            IRepository<ProcessManagementModel> processMqRepo,
            IRepository<AccountModel> accRepo,
            IRepository<DepartmentModel> deptRepo,
            IRepository<ProcessFlowDetailModel> processFlowDetailRepo,
            IMapper mapper,
            ILogger<AddProcessFlowHandler> logger
            )
        {
            _processFlowRepo = processFlowRepo;
            _processMqRepo = processMqRepo;
            _accRepo = accRepo;
            _deptRepo = deptRepo;
            this.processFlowDetailRepo = processFlowDetailRepo;
            _mapper = mapper;
            _logger = logger;

        }


        public async Task<ApiResult<int>> Handle(AddProcessFlowCommand request, CancellationToken cancellationToken)
        {
            var processes = new List<ProcessManagementModel>();
            foreach (var dto in request.Procedures)
            {
                var model = _mapper.Map<ProcessManagementModel>(dto);
                model.Id = YitIdHelper.NextId();
                processes.Add(model);
            }


            var processFlow = _mapper.Map<ProcessFlowModel>(request);
            processFlow.Id = YitIdHelper.NextId();
            processFlow.ProcessCount = processes.Count; // 设置工序数量

            var r1 = 0;
            var r2 = 0;
            var r3 = 0;
            using (var tran = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                try
                {
                    // 批量添加工序
                    r1 = await _processMqRepo.CreateRangeAsync(processes);

                    // 添加工艺流程
                    r2 = await _processFlowRepo.AddAsync(processFlow);


                    var flowDetails = processes.Select(p => new ProcessFlowDetailModel
                    {
                        Id = YitIdHelper.NextId(),
                        ProcessFlowId = processFlow.Id,
                        ProcessId = p.Id
                    }).ToList();


                    r3 = await processFlowDetailRepo.CreateRangeAsync(flowDetails);


                    tran.Complete();
                }
                catch (Exception ex)
                {
                    _logger.LogError($"发生异常，事务回滚：{ex.Message}");
                    throw;
                }
            }

            if (r1 > 0 && r2 > 0 && r3 > 0)
            {
                return new ApiResult<int>().Success("保存成功！", r1 + r2 + r3);
            }
            else
            {
                return new ApiResult<int>().Fail("保存失败！");
            }

        }
    }
}
